package com.walter.learn.ReadAndWrite;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.util.List;

/**
 * @ProjectName: learnOwner
 * @Package: com.walter.learn.ReadAndWrite
 * @ClassName: Write
 * @Description: java类作用描述
 * @Author: 唐朝
 * @CreateDate: 2019/2/19 15:36
 * @UpdateUser: 更新者
 * @UpdateDate: 2019/2/19 15:36
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
@Slf4j
public class Write {

    //使用FileWriter的方式写入文件
    public static void writeByFileWriter(String content, String fileName) {
        try {
            File file = new File(fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fw = new FileWriter(file, false);//不追加字符
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content);
            log.info("写入成功");
            bw.close();
            bw.flush();
            fw.close();

        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException();
        }
    }

    //使用FileWriter的方式写入文件(速度较快)
    public static void writeByFileOutputStream(String content, String fileName) {
        FileOutputStream fileOutputStream = null;
        File file = new File(fileName);
        try {
            if (file.exists()) {
                file.createNewFile();
            }
            fileOutputStream = new FileOutputStream(file, true);
            fileOutputStream.write(content.getBytes());
            fileOutputStream.flush();
            fileOutputStream.close();
            log.info("写入成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException();
        }

    }
}
